package com.egao.common.module.system.transfer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egao.common.core.web.JsonResult;
import com.egao.common.module.company.entity.Company;
import com.egao.common.module.company.entity.Position;
import com.egao.common.module.company.entity.vo.CompanyListVO;
import com.egao.common.module.company.service.CompanyService;
import com.egao.common.module.company.service.PositionService;
import com.egao.common.module.system.entity.User;
import com.egao.common.module.system.entity.UserRole;
import com.egao.common.module.system.service.UserRoleService;
import com.egao.common.module.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 职位数据导入
 * @author: dl
 */
@RestController
@Slf4j
public class PositionDataController {

    @Value("${old.datasource.jyurl}")
    private String url;

    @Value("${old.datasource.username}")
    private String userName;

    @Value("${old.datasource.password}")
    private String password;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private PositionService positionService;

    @Transactional(rollbackFor = Exception.class)
    public JsonResult transfer() {
        Connection conn = null;
        Statement st = null;
        ResultSet rs = null;
        long beginTime = System.currentTimeMillis();
        List<Company> companyList = getCompanyList();
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection(url, userName, password);
            st = conn.createStatement();
            String sql = "SELECT " +
                    "  id " +
                    ", company_id " +
                    ", type " +
                    ", name " +
                    ", number " +
                    ", address " +
                    ", major " +
                    ", degree " +
                    ", salary " +
                    ", content " +
                    ", state " +
                    ", create_date " +
                    ", create_by " +
                    ", update_date " +
                    ", update_by " +
                    ", remarks " +
                    ", del_flag " +
                    "FROM position";
            st = conn.createStatement();
            rs = st.executeQuery(sql);
            log.info("总数：{}", rs.getRow());
            int i = 0;
            while (rs.next()) {
                String oldId = rs.getString("id");
                String companyOldId = rs.getString("company_id");
                Integer companyId = getCompanyId(companyList, companyOldId);
                String type = rs.getString("type");
                String name = rs.getString("name");
                String number = rs.getString("number");
                String address = rs.getString("address");
                String major = rs.getString("major");
                String degree = rs.getString("degree");
                String salary = rs.getString("salary");
                String state = rs.getString("state");
                String del_flag = rs.getString("del_flag");

                Position position = new Position();
                Date createDate = new Date(rs.getTimestamp("create_date").getTime());
                if (rs.getTimestamp("update_date") != null) {
                    Date updateDate = new Date(rs.getTimestamp("update_date").getTime());
                    position.setUpdateTime(updateDate);
                }
                position.setOldId(oldId);
                position.setDeleted("0".equals(del_flag) ? 0 : 1);
                position.setCompanyId(companyId);
                position.setType(type);
                position.setName(name);
                position.setNumber(number);
                position.setAddress(address);
                if (major != null && major.split(",").length == 141) {
                    position.setMajor("专业不限");
                } else {
                    position.setMajor(major);
                }
                position.setDegree(degree);
                position.setState(state);
                position.setCreateTime(createDate);
                if (salary != null && salary.contains("~") && !salary.contains("面议")) {
                    position.setSalaryType("0");
                    // 小写转换
                    salary = salary.toLowerCase()
                            .replaceAll("\\.", "")
                            .replaceAll("\\+", "")
                            .replaceAll("&middot;", "")
                            .replaceAll(" ", "");
                    log.info(salary);
                    // 数据转换
                    if (salary.contains("k")) {
                        salary = salary.replaceAll("k", "000");
                    } else if (salary.contains("万")) {
                        salary = salary.replaceAll("万", "0000");
                    } else if (salary.contains("元")) {
                        salary = salary.replaceAll("元", "");
                    } else if (salary.contains("w")) {
                        salary = salary.replaceAll("w", "0000");
                    }
                    String[] array = salary.split("~");
                    String min = array[0].trim();
                    String max = array[1].trim();
                    if (max.contains("不等") || max.contains("以上")) {
                        max = min;
                    }
                    position.setSalaryMin(Integer.parseInt(min));
                    position.setSalaryMax(Integer.parseInt(max));

                } else if ("面议".equals(salary)) {
                    position.setSalaryType("1");
                } else if(salary != null && salary.contains("面议")) {
                    position.setSalaryType("1");
                } else if(salary == null) {
                    position.setSalaryType("0");
                } else {
                    // 异常数据
                    position.setSalaryType("2");
                }

                i ++;
                log.info("职位：{} 第：{} 个", name,i);
                if (positionService.save(position)) {
                    log.info("职位：{} 第：{} 个", name,i);
                }
            }
            long overTime = System.currentTimeMillis();
            long finishTime = (overTime - beginTime) / 1000;
            log.info("完成时间 : {} 分", finishTime);
            return JsonResult.ok(String.format("完成时间 : %s 分", finishTime));
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                rs.close();
                st.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return JsonResult.ok();
    }
    
    /** 
     * 查询所有单位信息
     * @return 
     */
    private List<Company> getCompanyList() {
        return companyService.list();
    }

    /**
     * 查询原始
     * @return
     */
    private Integer getCompanyId(List<Company> companyList, String oldId) {
        for(Company company : companyList) {
            if (oldId.equals(company.getOldId())) {
                return company.getId();
            }
        }
        return 0;
    }


}
